<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    :rules="rules"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submit">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { newDetailsInfo, saveUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      // 接收父组件路由传递过来的路径参数
      userId: this.$route.params.id,
      // 表单数据
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadDetailsInfo()
  },
  methods: {
    // 根据Id获得对应员工的信息
    async loadDetailsInfo() {
      try {
        const res = await newDetailsInfo(this.userId)
        // console.log('newDetailsInfo', res)
        // 保存数据
        this.userInfo = { ...res.data, password: '' }
      } catch (err) {
        console.log('newDetailsInfo', err)
      }
    },
    // 点击更新
    submit() {
      this.$refs.userForm.validate((valid) => {
        if (!valid) return
        this.loadUserDetailById()
      })
    },
    // 更新员工信息
    async loadUserDetailById() {
      try {
        const res = await saveUserDetailById(this.userInfo)
        // console.log('saveUserDetailById', res)
        // 保存数据
        if (res.code !== 10000) return
        this.$message.success(res.message)
        // vuex 用户数据重新发送获取
        this.$store.dispatch('user/axiosInfo')
        this.$router.back()
      } catch (err) {
        console.log('saveUserDetailById', err)
      }
    }
  }
}
</script>
